package com.qk.management.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.qk.common.dto.OSSObjectVersionDto;
import com.qk.common.util.AliYunOSSGetFiles;
import com.qk.common.util.AliyunOSSDelFils;
import com.qk.management.mapper.UserMapper;
import com.qk.management.service.OSSReconciliationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @文件名: OSSReconciliationService
 * @作者: DX
 * @创建日期: 2025/10/11
 * @描述:
 */
@Service
public class OSSReconciliationServiceImpl implements OSSReconciliationService {

    @Autowired
    private AliYunOSSGetFiles aliYunOSSGetFiles;

    @Autowired
    private AliyunOSSDelFils aliyunOSSDelFils;

    @Autowired
    private UserMapper userMapper;

    @Override
    public void reconcile() {
        List<OSSObjectVersionDto> ossObjectVersionDtos = aliYunOSSGetFiles.ossGetFiles();

        List<String> keyNames = CollUtil.getFieldValues(ossObjectVersionDtos, "keyName")
                .stream()
                .map(Object::toString)
                .toList();

        List<String> images = userMapper.getAllImages();

        List<String> fileNames = images.stream()
                .map(url -> StrUtil.subAfter(url, "/", true))
                .toList();

        List<String> missingInImages = CollUtil.subtractToList(keyNames, fileNames);



        List<OSSObjectVersionDto> missingInImagesDtos = ossObjectVersionDtos.stream()
                .filter(ossObjectVersionDto -> missingInImages.contains(ossObjectVersionDto.getKeyName()))
                .toList();

        aliyunOSSDelFils.batchDeleteVersions(missingInImagesDtos);
    }
}
